package com.wyp168.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @ClassName ParseBoolExprSolution
 * @Author wyp168
 * @Date 2022/11/5 11:13
 */
public class ParseBoolExprSolution {

    public static void main(String[] args) {
        ParseBoolExprSolution solution = new ParseBoolExprSolution();
        String expression = "&(t,f)";
        System.out.println(solution.parseBoolExpr(expression));
    }

    public boolean parseBoolExpr(String expression) {
        Deque<Character> stack = new ArrayDeque<>();
        return dfs(expression, stack);
    }
    Integer beginIndex = 0;
    public boolean dfs(String expression, Deque<Character> stack) {
        List<Boolean> tempResult = new ArrayList<>();
        boolean loop = true;
        while (loop && beginIndex < expression.length()) {
            char charVal = expression.charAt(beginIndex);
            if (charVal == '(') {
                stack.push(expression.charAt(beginIndex - 1));
                beginIndex ++;
                tempResult.add(dfs(expression, stack));
            } else if (charVal == ')' && !stack.isEmpty()) {
                Character express = stack.peek();
                if (express == '&') {
                    if (tempResult.contains(false)) {
                        tempResult = new ArrayList<>();
                        tempResult.add(false);
                    } else {
                        tempResult = new ArrayList<>();
                        tempResult.add(true);
                    }
                } else if (express == '|') {
                    if (tempResult.contains(true)) {
                        tempResult = new ArrayList<>();
                        tempResult.add(true);
                    } else {
                        tempResult = new ArrayList<>();
                        tempResult.add(false);
                    }
                } else if (express == '!') {
                    tempResult.set(0, !tempResult.get(0));
                }
                stack.poll();
                loop = false;
                continue;
            } else {
                if (charVal == 't') {
                    tempResult.add(true);
                } else if (charVal == 'f'){
                    tempResult.add(false);
                }
            }
            beginIndex ++;
        }
        return tempResult.get(0);
    }
}
